const {School, Area} = require('../db/model/index')
const {Op} = require('sequelize')

const getSchoolList = async ({name, pageIndex, pageSize, createTime, area_id}) => {
  const where = {
    name: {
      [Op.substring]: name
    }
  }

  if (createTime.length) {
    where[`created_at`] = {
      [Op.gte]: createTime[0],
      [Op.lte]: createTime[1]
    }
  }

  if (area_id.length) {
    where[`area_id`] = {
      [Op.in]: area_id
    }
  }

  const result = await School.findAndCountAll({
    limit: +pageSize,
    offset: pageSize * pageIndex,
    order: [
      [ 'id', 'desc' ]
    ],
    include: [
      {
        model: Area,
        attributes: [ 'name' ]
      }
    ],
    where
  })

  return {
    count: result.count,
    data: result.rows
  }
}
const getSchoolOne = async (id) => {
  const result = await School.findOne({
    where: {
      id
    },
    include: [
      {
        model: Area,
        attributes: [ 'name' ]
      }
    ]
  })

  return result.dataValues
}


const createSchool = async ({name, areaId}) => {
  const result = await School.create({
    name,
    areaId
  })

  const data = result.dataValues

  return data
}

const updateSchool = async ({name, areaId, id}) => {
  const whereOpt = {
    id
  }
  const result = await School.update({
    name,
    areaId
  }, {
    where: whereOpt
  })

  const data = result.length > 0

  return data
}

const delSchool = async (id) => {
  const result = await School.destroy({
    where: {
      id
    }
  })

  return result > 0
}

module.exports = {
  createSchool,
  getSchoolList,
  updateSchool,
  delSchool,
  getSchoolOne
}
